import axios from "axios";
import { useUserStoreHook } from "@/stores/modules/user";
import router from "@/router";
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.DEV ? '' : import.meta.env.VITE_API_URL,
  withCredentials: true,
  // withXSRFToken: true,
  timeout: 30000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
    "X-Requested-With": "XMLHttpRequest",
    "X-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone, // 时区
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    console.log(useUserStoreHook().token);
    console.log(JSON.parse(localStorage.getItem('user')));

    if (useUserStoreHook().token) {
      config.headers.Authorization = useUserStoreHook().token
    } else {
      const { token } = JSON.parse(localStorage.getItem('user') || "{}")
      if (token) {
        config.headers.Authorization = token;
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
const msgList = [403, 422, 500]
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
    if (response.config.responseType === "blob" || response.config.responseType === "arraybuffer") {
      return response;
    }
    const req = response.data;
    return req;
  },
  (error) => {
    const data = error.response
    console.log(data, error);
    if (msgList.includes(data.status)) {
      if (data.data.message) {
        ElMessage.error(data.data.message)
      } else {
        router.push(`/login`);
        useUserStoreHook().token = ''
      }
    } else if (data.status === 401) {
      router.push(`/login`);
      useUserStoreHook().token = ''
      ElMessageBox.alert("当前页面已失效，请重新登录").finally(() => {
      })
    } else {
      ElMessage.error('系统错误，请联系管理员')
    }
    return Promise.reject(data);
  }
);

// 导出 axios 实例
export default service;
